package pcp

import (
	"bytes"
	"compress/gzip"
	"io"
)

// MustGzip gzip压缩数据
func MustGzip(src []byte) (dist []byte) {
	dist, _ = Gzip(src)
	return
}

// Gzip gzip压缩数据
func Gzip(src []byte) (dist []byte, err error) {
	var buf bytes.Buffer

	writer := gzip.NewWriter(&buf)
	defer writer.Close()

	_, err = writer.Write(src)
	if err != nil {
		return
	}

	err = writer.Flush()
	if err != nil {
		return
	}

	dist = buf.Bytes()

	return
}

// MustGunzip 数据解压缩
func MustGunzip(src []byte) (dist []byte) {
	dist, _ = Gunzip(src)
	return
}

// Gunzip 数据解压缩
func Gunzip(src []byte) (dist []byte, err error) {
	reader, err := gzip.NewReader(bytes.NewBuffer(src))
	if err != nil {
		return
	}
	defer reader.Close()

	return io.ReadAll(reader)
}
